package com.tjetc.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tjetc.common.Resp;
import com.tjetc.dao.UserMapper;
import com.tjetc.entity.User;
import com.tjetc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public Resp login(User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        String type = user.getUserType();
        List<User> list = userMapper.getUserByUsername(username);
        if(list.size() != 0){
            User DBUser = list.get(0);
            if(DBUser.getPassword().equals(password) && DBUser.getUserType().equals(type)){
                return Resp.ok().data("status","登录成功！").data("info",DBUser);
            }else if(!DBUser.getPassword().equals(password)){
                return Resp.error().data("status","密码错误！");
            }else if(!DBUser.getUserType().equals(type)){
                return Resp.error().data("status","身份选择错误！");
            }
        }
        return Resp.error().data("status","该用户不存在！");
    }

    @Override
    public Resp register(User user) {
        List<User> list = userMapper.getUserByUsername(user.getUsername());
        if(list.size() == 0){
            if(userMapper.insertUser(user) != 0){
                return Resp.ok().data("status","注册成功！");
            }else {
                return Resp.error().data("status","注册失败！");
            }
        }
        return Resp.error().data("status","用户名已存在！");
    }

    @Override
    public Resp edit(User user) {
        List<User> list = userMapper.getUserByUsername(user.getUsername());
        if(list.size() == 0 || user.getId() == list.get(0).getId()){
            int isSuc = userMapper.editUser(user);
            if(isSuc == 1){
                return Resp.ok().data("status","保存成功！");
            }else {
                return Resp.error().data("status","保存失败！");
            }
        }
        return Resp.error().data("status","用户名重复！");
    }

    @Override
    public Resp delete(int id) {
        int isSuc = userMapper.deleteById(id);
        if(isSuc == 1){
            return Resp.ok().data("status","删除成功！");
        }
        return Resp.error().data("status","删除失败！");
    }

    @Override
    public Resp getAll() {
        return Resp.ok().data("userList",userMapper.getAllExceptAdmin());
    }
}
